package App.Model;

import App.Model.Tool.DosTool;
import App.Model.Tool.SwingUtil;
import App.Model.message.Message;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.jar.JarEntry;

//为用户本地存储开发,在本地文件中读取与写入用户聊天记录
public class ArisuClientDB {
   // private static String userId;//目标用户
    //private static HashMap<String, List<Message>> conversations;//key 聊天对象
    private static HashMap<String,ImageIcon> userHeaders;//key: headerUserName | value: headerImg

    static {
        userHeaders = readHeadersAtFile();
        if(userHeaders == null){
            userHeaders = new HashMap<>();
        }


    }

    //将conversations写入文件
    public static boolean saveConversationToFile(String userId, HashMap<String, List<Message>> conversations) {
        String url = "src\\main\\resources\\data\\" + userId + "conversations.ser";
        try (
                FileOutputStream fos = new FileOutputStream(url);
                ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(conversations);

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //从外部文件获取conversations
    public static HashMap<String, List<Message>> readConversationToFile(String userId) {
        String url = "src\\main\\resources\\data\\" + userId + "conversations.ser";
        HashMap<String, List<Message>> readToFileData = null;
        Path filePath = Paths.get(url);
        try {
            // 检查文件是否存在并且其大小大于0
            if (Files.exists(filePath) && Files.size(filePath) > 0) {
                try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath.toFile()))) {
                    Object obj = in.readObject(); // 你的Object对象
                    readToFileData = (HashMap<String, List<Message>>) obj;
                    System.out.print("加载历史聊天数据...");
                    if (readToFileData.size() == 0) {
                        System.out.println("所有历史消息为空");
                        return null;
                    }
                    System.out.println("成功加载聊天数据");
                    return readToFileData;
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                    return null;
                }
            } else {
                System.out.println("所有历史消息为空");
                return null; // 或者你可以返回一个空的HashMap，取决于你的需求
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //将用户提醒写入文件
    public static void saveConformToFile(String userId, HashMap<String, Boolean> conforms) {
        String url = "src\\main\\resources\\data\\conformData\\" + userId + "conforms.ser";
        try (
                FileOutputStream fos = new FileOutputStream(url);
                ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(conforms);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //从文件中读取用户提醒
    public static HashMap<String, Boolean> readConformToFile(String userId) {
        String url = "src\\main\\resources\\data\\conformData\\" + userId + "conforms.ser";
        HashMap<String, Boolean> readToFileData = null;
        Path filePath = Paths.get(url);
        try {
            // 检查文件是否存在并且其大小大于0
            if (Files.exists(filePath) && Files.size(filePath) > 0) {
                try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath.toFile()))) {
                    Object obj = in.readObject(); // 你的Object对象
                    readToFileData = (HashMap<String, Boolean>) obj;
                    System.out.print("加载用户提醒...");
                    if (readToFileData.size() == 0) {
                        System.out.println("用户提醒为空");
                        return null;
                    }
                    System.out.println("成功加载用户提醒");
                    return readToFileData;
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                    return null;
                }
            } else {
                System.out.println("用户提醒为空");
                return null; // 或者你可以返回一个空的HashMap，取决于你的需求
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static boolean cleanAllConversationToFile(String userId) {//将某个用户的所有缓存历史消息清除
        String url = "src\\main\\resources\\data\\" + userId + "conversations.ser";
        try (
                FileOutputStream fos = new FileOutputStream(url);
                ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(null);

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static void saveUserHeaderToFile(byte[] headerData,String fileType,String userId){
        //保存头像文件
        String url = "src\\main\\resources\\recourse\\header\\" + userId + "." + fileType;
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(url);
            fileOutputStream.write(headerData);
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static ImageIcon getUserHeaderAtFile(String userId){
        //从文件中读取头像
        System.out.println("读取 " + userId + " 的头像信息");
        File file = DosTool.GetCorrectFilename("src\\main\\resources\\recourse\\header\\",userId);
        if(file == null){
            return null;
        }
        String path = file.getPath();
        System.out.println(path);
        return SwingUtil.createAutoAdjustIcon(path,true);
    }

    public static ImageIcon getHeaderImg(String userId){
        return userHeaders.get(userId);
    }

    public static void  putDataToHeaderImg(String userId,byte[] data){
        ImageIcon imageIcon;
        try {
            // 将byte[]转换为InputStream
            ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
            // 从InputStream创建BufferedImage
            BufferedImage bufferedImage = ImageIO.read(inputStream);
            // 使用BufferedImage创建ImageIcon
            imageIcon = SwingUtil.createAutoAdjustIcon(bufferedImage,true);
            userHeaders.put(userId,imageIcon);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static HashMap<String, ImageIcon> readHeadersAtFile(){
        String url = "src\\main\\resources\\recourse\\header\\headers.ser\\";
        HashMap<String, ImageIcon> readToFileData = null;
        Path filePath = Paths.get(url);
        try {
            // 检查文件是否存在并且其大小大于0
            if (Files.exists(filePath) && Files.size(filePath) > 0) {
                try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(filePath.toFile()))) {
                    Object obj = in.readObject(); // 你的Object对象
                    readToFileData = (HashMap<String, ImageIcon>) obj;
                    System.out.print("加载用户头像...");
                    if (readToFileData.size() == 0) {
                        return null;
                    }
                    return readToFileData;
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                    return null;
                }
            } else {
                return null; // 或者你可以返回一个空的HashMap，取决于你的需求
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void saveHeadersToFile(){
        String url = "src\\main\\resources\\recourse\\header\\headers.ser\\";
        try (
                FileOutputStream fos = new FileOutputStream(url);
                ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            oos.writeObject(userHeaders);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static HashMap<String, ImageIcon> getUserHeaders() {
        return userHeaders;
    }
}
